﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBR.Common;
using TBR.Entities;

namespace TBR.Repositories
{
    public class ProfileRepository
    {
        private UserDetails Profile = null;
        private HtmlHelper htmlhelper = null;
        private WebHelper webhelper = null;
        private string HtmlResponse = String.Empty;
        private bool isMyProfile = false;

        #region constructor
        public ProfileRepository()
        {
            this.webhelper = new WebHelper();
            this.htmlhelper = new HtmlHelper();
        }
        #endregion

        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public UserDetails Profile;
        }
        #endregion

        #region ProfileLoadPageCompleted
        public event RequestEventHandler GetProfilePageCompleted;
        public void OnGoProfilePageCompleted()
        {
            if (GetProfilePageCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.Profile = Profile;
                GetProfilePageCompleted(this, args);
            }
        }
        private void webhelper_GoProfilePageCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webhelper_GoProfilePageCompleted;

            string strProfile;
            if (isMyProfile)
                strProfile = htmlhelper.GetHtml(args.HtmlCode, "Редактировать анкету", "Подробнее обо мне");
            else
                strProfile = htmlhelper.GetHtml(args.HtmlCode, "search.php", "Подробнее обо мне &gt;&gt;</a>");
            Profile = ExtractProfile(strProfile);
            OnGoProfilePageCompleted();
        }
        #endregion

        #region public methods
        public void GetProfile(string userId = "")
        {
            isMyProfile = userId == String.Empty;

            webhelper.RequestCompleted += webhelper_GoProfilePageCompleted;

            Uri uri = GetUri(userId);
            webhelper.GetHtmlCode(uri, WebHelper.Method.Get);
        }

        public void SetState(string stateText)
        {
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            Dictionary<string, string> dicPostParams = new Dictionary<string, string>();
            dicPostParams.Add("status_text", stateText);
            webhelper.GetHtmlCode(new Uri(String.Format("http://tabor.ru/status/change.php?sid={0}", sid)), WebHelper.Method.Post, dicPostParams);
        }

        private static Uri GetUri(string userId)
        {
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            Uri uri;
            if (userId != String.Empty)
                uri = new Uri(String.Format("http://tabor.ru/profile.php?id={0}&sid={1}", userId, sid));
            else
                uri = new Uri(String.Format("http://tabor.ru/profile.php?sid={1}", userId, sid));
            return uri;
        }

        #endregion

        #region private methods
        private UserDetails ExtractProfile(string strProfile)
        {
            string id = GetId(strProfile);
            string friendName = GetName(strProfile);
            ESex sex = GetSex(strProfile);
            string imgUrl = GetImageUrl(strProfile);
            int age = GetAge(strProfile);
            string location = GetLocation(strProfile);
            string actionDate = GetActionDate(strProfile);
            ESexualOrientation sexualOrientation = GetSexualOrientation(strProfile);
            string search = GetSearch(strProfile);
            string searchObjectAge = GetSearchObjectAge(strProfile);
            string mission = GetMission(strProfile);
            string aboutMyself = GetAboutMyself(strProfile);
            string state = GetState(strProfile);

            MainDetatilsOfUser details = new MainDetatilsOfUser(aboutMyself, state, sexualOrientation, search, searchObjectAge, mission);
            return new UserDetails(id, friendName, imgUrl, age, location, sex, actionDate, details);

        }
        public string GetAboutMyself(string text)
        { 
            try
            {
                if (text.IndexOf("О себе:</span>") == -1) throw new NotImplementedException();

                string begin = "О себе:</span>";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                text = text.Remove(text.IndexOf("<"));
                if (text.LastIndexOf('[') + 1 == text.Length)
                {
                    text = text.Remove(text.Length - 1);
                }
                return text;
            }
            catch
            {
                return String.Empty;
            }
      
        }

        public string GetState(string text)
        {
            try
            {
                if (text.IndexOf("status.png") == -1) throw new NotImplementedException();

                string end = "<a href=\"photos.php";
                text = text.Remove(text.IndexOf(end));
                end = "</a>";
                text = text.Remove(text.LastIndexOf(end));

                return text.Substring(text.LastIndexOf('>')+1);
            }
            catch
            {
                return String.Empty;
            }
        }
        private string GetMission(string text)
        {
            try
            {
                if (text.IndexOf("Цель знакомства: </span>") == -1) throw new NotImplementedException();

                string begin = "Цель знакомства: </span>";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return text.Remove(text.IndexOf("<"));
            }
            catch
            {
                return String.Empty;
            }
        }

        private string GetSearchObjectAge(string text)
        {
            try
            {
                if (text.IndexOf("В возрасте: </span>") == -1) throw new NotImplementedException();

                string begin = "В возрасте: </span>";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return text.Remove(text.IndexOf("<"));
              
            }
            catch
            {
                return String.Empty;
            }
        }

        private string GetSearch(string text)
        {
            try
            {
                if (text.IndexOf("Ищу: </span>") == -1) throw new NotImplementedException();

                string begin = "Ищу: </span>";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return text.Remove(text.IndexOf("<"));
            }
            catch
            {
                return String.Empty;
            }
        }

        private ESexualOrientation GetSexualOrientation(string strProfile)
        {
            try
            {
                string begin = "Ориентация: </span>";

                strProfile = strProfile.Remove(0, strProfile.IndexOf(begin) + begin.Length);
                strProfile = strProfile.Remove(strProfile.IndexOf("<"));

                switch (strProfile.ToLower())
                {
                    case "гетеро": return ESexualOrientation.Getero; break;
                    case "би": return ESexualOrientation.Bi; break;
                    case "гей": return ESexualOrientation.Gay; break;
                    default: return ESexualOrientation.None;
                }
            }
            catch
            {

                return ESexualOrientation.None;
            }
        }

        private string GetName(string text)
        {
            try
            {
                string begin = "> <b>";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return text.Remove(text.IndexOf("<"));
            }
            catch
            {
                return string.Empty;
            }
        }

        private string GetId(string text)
        {
            try
            {
                string begin = "uid=";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return text.Remove(text.IndexOf("&amp"));
            }
            catch
            {
                return string.Empty;
            }
        }

        private ESex GetSex(string text)
        {
            return text.IndexOf("boy.png") != -1 ? ESex.Male : ESex.Female;
        }

        private string GetImageUrl(string text)
        {
            try
            {
                string differentNameServer = "http://i2";
                string begin = "tabor.ru/photos";
                string end = "\"";
                text = text.Remove(0,text.IndexOf(begin)-differentNameServer.Length);
                text = text.Remove(text.IndexOf(end));

                return String.Format("h{0}", text.Substring(text.IndexOf("ttp"))); 
            }
            catch
            {
                return string.Empty;
            }
        }

        private int GetAge(string text)
        {
            try
            {
                string begin = "<b>";
                string end = "</b> | <a";
                text = text.Remove(text.IndexOf(end));
                text = text.Remove(text.LastIndexOf(" "));
                return int.Parse(text.Remove(0, text.LastIndexOf(begin) + begin.Length));
            }
            catch
            {
                return 0;
            }
        }

        private string GetLocation(string text)
        {
            try
            {
                string end = "</b> <img src=";
                text = text.Remove(text.IndexOf(end));
                return text.Remove(0, text.LastIndexOf(">") + ">".Length);
            }
            catch
            {
                return String.Empty;
            }
        }
        private string GetActionDate(string text)
        {
            int startSpanIndex = text.IndexOf("<span");
            int endSpanIndex = text.IndexOf("</span>");
            if (startSpanIndex != -1 && endSpanIndex != -1 && startSpanIndex < endSpanIndex)
            {
                
                string span = text.Substring(startSpanIndex+1, endSpanIndex - startSpanIndex);
                span = span.Replace("<b>", "").Replace("</b>", "");
                int startIndex = span.LastIndexOf(">") + 1;
                int endIndex = span.LastIndexOf("<");
                return span.Substring(startIndex, endIndex - startIndex);
            }
            else return String.Empty;
        }

      
        #endregion
    }
}
